package com.lr.server.demo1;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;

/*
 * response的封装
 */
public class Response {

    private static final String CRTL = "\r\n";
	
	private static final String BLANK = " ";
	
	private StringBuilder response;
	
	private StringBuilder responseContext;
	
	private int length;
	
	private BufferedWriter bw;
	
	private int error = 0;

	public Response() {
		super();
		response = new StringBuilder();
		responseContext = new StringBuilder();
		length = 0;
	}
	
	public Response(Socket socket) {
		this();
		try {
			bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
		} catch (IOException e) {
			error = 500;
		}
	}
	
	//构建正文
	public Response createResponseContext(String info){
		responseContext.append(info);
		length += info.toString().getBytes().length;
		return this;
	}
	
	public Response createResponseContextCRTL(String info){
		responseContext.append(info).append(CRTL);
		length += (info + CRTL).toString().getBytes().length;
		return this;
	}
	
	public void createResponseHeader(int code){
		//1.Htpp协议/版本   响应码  描述
		response.append("HTTP/1.1").append(BLANK).append(code).append(BLANK);
		switch(code){
		case 200:
			response.append("OK");
			break;
		case 404:
			response.append("NOT FOUND");
			break;
		case 500:
			response.append("SERVER REEOR");
			break;
		}
		//2.响应头
		response.append("Accept-Ranges:bytes").append(CRTL);
		response.append("Age:12").append(CRTL);
		response.append("Cache-Control:max-age=315360000").append(CRTL);
		response.append("Connection:keep-alive").append(CRTL);
		response.append("Content-Encoding:utf-8").append(CRTL);
		response.append("Content-Length:").append(length).append(CRTL);
		response.append("Content-Type:text/html").append(CRTL);
		response.append("Date:").append(new Date()).append(CRTL);
		response.append("Server:bfe/1.0.8.13-sslpool-patch").append(CRTL);
		response.append("Vary:Accept-Encoding,User-Agent").append(CRTL);
		response.append(CRTL);
	}
	
	public void response(int code){
		if(error != 0){
			createResponseHeader(error);
		}
		createResponseHeader(code);
		try {
			bw.append(response.toString());
			bw.append(responseContext.toString());
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void colse(){
		IOUtil.IOClose(bw);
	}
}
